const fs = require('fs');
const path = require('path');
const readline = require('node:readline');
let notFound = []

function findKeyByValue(obj, value) {
  return Object.keys(obj).find(key => obj[key] === value);
}
function setTemplate (initContent, path) {
  let text = ''
  const lines = initContent.split(/\r?\n/);
  lines.forEach((line, index) => {
    if (line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--')) {
      text += '\n' + line
      return
    }
    if (!/[\u4E00-\u9FFF]/.test(line)) {
      text += '\n' + line
      return
    }

    /* 特殊处理内容*/
    line = line.replace(/format="yyyy 年 MM 月 dd 日"/g, (content, a, b, chinese) => {
      return `:format="\`yyyy \${$t('mmDdYyyy')}\`"`
    })
    line = line.replace(/([\w-]+)="(\s+)?((\d?\w?\s?[\u4E00-\u9FFF]?[“,，。、)(：.\-”]?)+)"/g, (content, a, b, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        return `:${a}="$t('${res}')"`
      }
      return content
    })
    line =  line.replace(/:([\w-]+)="`(\s+)?([\u4E00-\u9FFF]+)/g, (content, a, b, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = content.replace(chinese, `\${$t('${res}')}`)
      } else {
        console.log('chinese', chinese)
      }
      return content
    })
    line = line.replace(/([\w-]+)="(\s+)([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.”]?)+)"/g, (content, a, b, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
     if (res) {
       return `:${a}="$t('${res}')"`
     } else {
       addNotFound(chinese, path)
     }
     return content
    })
    /* 标签参数 */
    line = line.replace(/([\w-]+)="(([“`,，。、)(：.”]?)[\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.”]?)+)"/g, (content, a, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        return `:${a}="$t('${res}')"`
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    /* 标签 + 三元 */
    line = line.replace(/'([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.”]?)+)'/g, (content, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = content.replace(`'${chinese}'`, `$t('${res}')`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    line = line.replace(/`((\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.${}”]?)+)`/g, (content) => {
      content.replace(/([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.”]?)+)/g, (chinese) => {
        chinese = chinese.trim()
        const res = findKeyByValue(zh, chinese)
        if (res) {
          content = content.replace(chinese, `\${$t('${res}')}`)
        } else {
          addNotFound(chinese, path)
        }
      })
      return content
    })
    /* 标签内容 */
    line = line.replace(/(?<!')(?<!")([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“`,，。、)(：.”]?)+)/g, (content,chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = content.replace(chinese, `{{$t('${res}')}}`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    text += '\n' + line
  });
  return text
}
function addNotFound (chinese, path) {
  if (typeof path === 'string') {
    notFound.push({chinese, path})
  } else {
    notFound.push({chinese, path: ''})
  }
}
function getProps (content) {
  let text = ''
  const lines = content.split(/\r?\n/);
  let templateNum = 0
  let templateEndNum = 0
  let propsType = false

  let defaultType = false
  let i18nType = false
  lines.forEach((line) => {
    if (!defaultType) {
      if (!(line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--'))) {
        line = line.replace(/'([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)'/g, (content, chinese) => {
          chinese = chinese.trim()
          const res = findKeyByValue(zh, chinese)
          if (res) {
            if (!i18nType) {
              i18nType = true
            }
            content = content.replace(`'${chinese}'`, `i18n.t('${res}')`)
          } else {
            addNotFound(chinese, path)
          }
          return content
        })
      }
    }
    if (line.includes(`export default`)) {
      defaultType = true
    }

    if (line.includes(`props:`)) {
      propsType = true
    }
    if (!propsType) {
      text += '\n' + line
      return
    }
    if (!(line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--'))) {
      line = line.replace(/'([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)'/g, (content, chinese) => {
        chinese = chinese.trim()
        const res = findKeyByValue(zh, chinese)
        if (res) {
          if (!i18nType) {
            i18nType = true
          }
          content = content.replace(`'${chinese}'`, `i18n.t('${res}')`)
        } else {
          addNotFound(chinese, path)
        }
        return content
      })
    }
    if (line.includes(`{`)) {
      templateNum++
    }
    if (line.includes(`}`)) {
      templateEndNum++
      if (templateNum === templateEndNum) {
        propsType = false
      }
    }
    text += '\n' + line
  });
  if (i18nType) {
    return `
     import i18n from '@/lang' 
     ${text}
    `
  } else {
    return text
  }
}
/* 处理 vue 文件的 js */
function setVueScript (initContent, path) {
  initContent = getProps(initContent)
  let text = ''
  const lines = initContent.split(/\r?\n/);
  lines.forEach((line, index) => {
    if (line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--')) {
      text += '\n' + line
      return
    }
    if (line.includes('import') || line.includes('require(')) {
      text += '\n' + line
      return
    }
    /* 处理导入的xls文件 */
    line = line.replace(/.replace\(\/"(\w+)?([\u4E00-\u9FFF]+)":\/\g,/g, (content, a,chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        if (a) {
          return `.replace(new RegExp(\`"${a}\${this.$t('${res}')}":\`, 'g'),`
        } else {
          return `.replace(new RegExp(\`"\${this.$t('${res}')}":\`, 'g'),`
        }
      } else {
        console.log('content', content)
      }
      return content
    })
    /* 标签 + 三元 */
    line = line.replace(/'([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)'/g, (content, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = content.replace(`'${chinese}'`, `this.$t('${res}')`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })

    /* 标签内容 */
    const test = /([\u4E00-\u9FFF]+)/g
    if (test.test(line) && line.includes(`'`)) {
      line = line.replace(/'/g, `\``)
    }
    line = line.replace(/(?<!')(?<!")([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)/g, (content,chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = content.replace(chinese, `\${this.$t('${res}')}`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    text += '\n' + line
  });
  return text
}
/* 处理 version 版本文件的 js */
function setVersionScript (initContent, path) {
  let text = ''
  const lines = initContent.split(/\r?\n/);
  lines.forEach((line, index) => {
    if (line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--')) {
      text += '\n' + line
      return
    }
    if (line.includes('import') || line.includes('require(')) {
      text += '\n' + line
      return
    }
    if (line.includes('typeof') && line.includes('window')) {
      text += '\n' + line
      if (!initContent.includes(`require('@/lang')`)) {
        text += '\n' + `  const i18n = require('@/lang')`
      }
      return
    }
    /* 标签内容 */
    const test = /([\u4E00-\u9FFF]+)/g
    if (test.test(line) && line.includes(`'`)) {
      line = line.replace(/'/g, `\``)
    }
    line = line.replace(/`([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)`/g, (content,chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        content = `i18n.default.t('${res}')`
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    text += '\n' + line
  });
  return text
}
/* 处理其他js */
function setScript (initContent, path) {
  let text = ''
  const lines = initContent.split(/\r?\n/);
  let i18nType = false
  lines.forEach((line, index) => {
    if (line.includes('console.') || line.includes('//') || line.includes('/*') || line.includes('* ') || line.includes('<!--')) {
      text += '\n' + line
      return
    }
    if (line.includes('import') || line.includes('require(')) {
      text += '\n' + line
      return
    }
    /* 标签 + 三元 */
    line = line.replace(/'([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)'/g, (content, chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        if (!i18nType) {
          i18nType = true
        }
        content = content.replace(`'${chinese}'`, `i18n.t('${res}')`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })

    /* 标签内容 */
    const test = /([\u4E00-\u9FFF]+)/g
    if (test.test(line) && line.includes(`'`)) {
      line = line.replace(/'/g, `\``)
    }
    line = line.replace(/(?<!')(?<!")([\u4E00-\u9FFF](\s?[\u4E00-\u9FFF]?\d?\w?[“,，。、)(：.”]?)+)/g, (content,chinese) => {
      chinese = chinese.trim()
      const res = findKeyByValue(zh, chinese)
      if (res) {
        if (!i18nType) {
          i18nType = true
        }
        content = content.replace(chinese, `\${i18n.t('${res}')}`)
      } else {
        addNotFound(chinese, path)
      }
      return content
    })
    text += '\n' + line
  });
  if (i18nType && !text.includes(`'@/lang'`)) {
    return `
     import i18n from '@/lang' 
     ${text}
    `
  } else {
    return text
  }
}

/* 将最后一个 </template> 替换成 </1111template> */
function setData(initContent) {
  notFound = []
  let text = ''
  const lines = initContent.split(/\r?\n/);
  let templateNum = 0
  let templateEndNum = 0
  let oneLine = null
  lines.forEach((line, index) => {
     if (line.includes(`<template`)) {
       templateNum++
     }
    if (line.includes(`</template`)) {
      templateEndNum++
      if (templateNum === templateEndNum) {
        line = line.replace(`</template`, `</1111template`)
      }
    }
    if (index === 0 && line.includes('<!--')) {
      oneLine = line
    } else {
      text += '\n' + line
    }
  });
  return { text, oneLine}
}
function setWriteFile (path, data) {
  fs.writeFile(path, data, 'utf8', (err) => {
    if (err) {
      console.error(err);
      return;
    }
  });
}

async function setVueFile (path) {
  fs.readFile(path, 'utf8', async (err, data) => {
    if (err) {
      return;
    }
    let newData = ''
    const initData = setData(data)
    if (initData.oneLine) {
      newData += initData.oneLine
    }
    data = initData.text
    data = data.replace(new RegExp('<template[^>]*>([\\s\\S]*?)<\/1111template>', 'g'), (match, initContent) => {
      newData +=  `
        <template>${setTemplate(initContent, path)}
        </template>
    `
      return ''
    });
    data = data.replace(new RegExp('<script[^>]*>([\\s\\S]*?)<\/script>', 'g'), (match, initContent) => {
      newData +=  `
        <script>${setVueScript(initContent, path)}
        </script>
    `
      return ''
    });
    newData += data
    fs.writeFile(path, newData, 'utf8', (err) => {
      if (err) {
        console.error(err);
        return;
      }
      ('执行成功')
    });
  });
}
async function setJsFile (path, type) {
  fs.readFile(path, 'utf8', async (err, data) => {
    if (err) {
      return;
    }
    let newData = ''
    if (type === 'version') {
      newData += setVersionScript(data, path)
    } else if (type === 'vue') {
      newData += setVueScript(data, path)
    } else {
      newData += setScript(data, path)
    }
    fs.writeFile(path, newData, 'utf8', (err) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log('执行成功')
    });
  });
}
function readFilesRecursively(folderPath) {
  const files = fs.readdirSync(folderPath);
  files.forEach(file => {
    const filePath = path.join(folderPath, file);
    const stats = fs.statSync(filePath);
    if (stats.isDirectory()) {
      readFilesRecursively(filePath);
    } else if (stats.isFile()) {
      //
      if (!(filePath.includes('micro-app.js'))){
        const list = filePath.split('.')
        const suffix = list[list.length - 1]
        if (suffix === 'vue') {
          // 在这里处理文件
          setVueFile(filePath)
        } else if (suffix === 'js') {
          if (filePath.includes('version')) {
            setJsFile(filePath, 'version')
          } else if (filePath.includes('components') || filePath.includes('views')){
            setJsFile(filePath, 'vue')
          } else {
            setJsFile(filePath)
          }
        }
      }
    }
  });
}

const zh = require('D:\\gitee项目\\微前端调度台\\新建文件夹\\command-main\\src\\lang\\zh_CN.json')
const folderPath = 'D:\\gitee项目\\微前端调度台\\新建文件夹\\command-main\\src';
readFilesRecursively(folderPath);
